package com.cnxdc.demo.controller;

import com.cnxdc.demo.service.UserService;
import com.cnxdc.demo.utils.JwtUtil;
import com.cnxdc.demo.utils.Md5Util;
import com.cnxdc.demo.utils.ThreadLocalUtil;
import com.cnxdc.demo.vo.Result;
import com.cnxdc.demo.vo.User;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/register")
    public Result<User> register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        // 直接调用service做完全的业务处理： 前些年：java百家争鸣的时候！！！ ：追求完美
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        return userService.doRegister(user);
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        User u = userService.findUserByUsername(username);
        if (u == null) {
            return Result.error("用户不存在");
        }
        password= Md5Util.getMD5String(password);
        if (!u.getPassword().equals(password)) {
            return Result.error("密码不正确");
        }
        // 我们要返回内容!!!
        Map<String, Object> map = new HashMap<>();
        map.put("id", u.getId());
        map.put("username", u.getUsername());

        String token = JwtUtil.genToken(map);
        //将发放给客户端的token存入到redis中,并且设置失效时间:防止数据太多!!!
        redisTemplate.opsForValue().set(u.getUsername(), token, 12, TimeUnit.HOURS);

        return Result.success(token);
    }
    @GetMapping("/userInfo")
    public Result<User> getUserInfo() {
        Map<String,Object> map = ThreadLocalUtil.get();
        String name= (String) map.get("username");
        //查询用户
        User user = userService.findUserByUsername(name);
        return Result.success(user);
    }
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.update(user);
        return Result.success();
    }
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@URL String avatarUrl) {
        userService.updatePic(avatarUrl);
        return Result.success();
    }
    @PatchMapping("/updatePwd")
    public Result updatePwd(String old_pwd, String new_pwd) {
        //查询用户
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findUserByUsername(username);
        //判断用户的旧密码和用户密码是否相同，如果相同，更新密码
        old_pwd = Md5Util.getMD5String(old_pwd);//变成密文再比较
        if (old_pwd.equals(user.getPassword())) {
            userService.updatePassword(user.getId(),new_pwd);

            //清除掉原来的token
            redisTemplate.opsForValue().getOperations().delete(username);

            return Result.success();
        }
        //否则 提示旧密码错误
        return Result.error("原密码不正确");
    }
}
